﻿using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace MyService
{
    public partial class HtxService : ServiceBase
    {
        private IScheduler scheduler;
        private readonly string TaskPlan;
        public HtxService()
        {
            InitializeComponent();
            // 新建一个调度器工工厂
            ISchedulerFactory factory = new StdSchedulerFactory();
            // 使用工厂生成一个调度器
            scheduler = factory.GetScheduler().Result;
            // 读取任务计划调度计划
            TaskPlan = ConfigurationManager.AppSettings["TaskPlan"];
        }

        protected override void OnStart(string[] args)
        {
            if (!scheduler.IsStarted)
            {
                //启动调度器
                scheduler.Start();
                //新建一个任务
                IJobDetail job = JobBuilder.Create<MyJob>().WithIdentity("TaskJob", "TaskJobGroup").Build();
                //新建一个触发器
                ITrigger trigger = TriggerBuilder.Create().StartNow().WithCronSchedule(TaskPlan).Build();
                //将任务与触发器关联起来放到调度器中
                scheduler.ScheduleJob(job, trigger);
            }
        }

        protected override void OnStop()
        {
            if (!scheduler.IsShutdown)
            {
                scheduler.Shutdown();
            }
        }
    }
}
